package com.ruyiadmin.springcloud.producer.common.utils.system;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.experimental.UtilityClass;

/**
 * <p>
 * Sentinel工具类
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-11-04
 */
@UtilityClass
public class RuYiSentinelUtil {

    //region 尝试限流、降级

    /**
     * <p>
     * 尝试限流、降级
     * </p>
     *
     * @param name 限流名称
     */
    public void tryAcquire(String name) throws BlockException {
        Entry entry = null;
        try {
            entry = SphU.entry(name);
        } catch (BlockException e) {
            // 如果没有通过走到了这里，就表示请求被限流，这里进行降级操作
            e.printStackTrace();
            throw e;
        } finally {
            if (null != entry) {
                entry.close();
            }
        }
    }

    //endregion

}
